package com.shuimin.service;

import com.shuimin.service.model.customer_service.SurveyAnswer;
import com.shuimin.service.model.customer_service.SurveyQuestion;
import pond.common.S;
import pond.db.Record;
import pond.db.sql.Criterion;
import pond.db.sql.Sql;
import pond.db.sql.SqlSelect;
import pond.web.Render;
import pond.web.Router;

import java.util.List;

import static pond.db.sql.Sql.selectFromRequest;


/**
 * Created by sky on 2017/6/6.
 */
public class QUESTION_ANSWER extends Router {

    {
        get("/search_question", (req, resp) -> App.DB.post(t -> {
            SqlSelect sqlSelect = selectFromRequest(req.toMap(), SurveyQuestion.class);
            resp.render(Render.page(
                    S._for(
                            t.query(SurveyQuestion.class, sqlSelect))
                            .map(SurveyQuestion::view)
                            .toList(),
                    t.count(sqlSelect.count())));
        }));

        get("/answer/:question_id", (req, resp) -> {
            String question_id = req.param("question_id");
            List<SurveyAnswer> list=App.DB.get(t -> {
                SqlSelect sql = Sql.select("*").from(SurveyAnswer.class);
                sql.where("question_id", Criterion.EQ, question_id);
                sql.orderBy("sn asc");
                return t.query(SurveyAnswer.class,sql);
            });
            resp.render(Render.json(list));
        });

        post("/create_question", (req, resp) -> {
            SurveyQuestion sq = (SurveyQuestion) Record.newEntity(SurveyQuestion.class).merge(req.toMap());
            App.DB.post(t -> t.recordInsert(sq));
            resp.render(Render.json(sq));
        });

        post("/create_answer/:question_id", (req, resp) -> {
            String question_id = req.paramNonBlank("question_id", "question_id can not be null!");
            SurveyAnswer sa = (SurveyAnswer) Record.newEntity(SurveyAnswer.class).merge(req.toMap());
            sa.set("question_id", question_id);
            App.DB.post(t -> t.recordInsert(sa));
            resp.send(200);
        });
    }

}
